﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
using ComicQ.Controller;
using ComicQ.Domain.Table;
using Microsoft.Win32;

namespace ComicQ.Dektop.View
{
    /// <summary>
    /// Interaction logic for ComicEditorView.xaml
    /// </summary>
    public partial class ComicEditorView
    {
        private readonly ComicController _comicControl;
        private readonly AuthorController _authorControl;
        private readonly PublisherController _publisherControl;
        private readonly YearController _yearControl;
        private readonly RentController _rentControl;
        private readonly ComicStatusController _comicStatusControl;

        private readonly IList<Author> _authors;
        private readonly IList<Publisher> _publishers;
        private readonly IList<Year> _years;
        private readonly IList<Rent> _rents;
        private readonly IList<ComicStatus> _comicStatuses;

        private readonly Comic _comic;

        private string _imageUrl;
        private readonly string _oldImageUrl;
        private Stream _readImage;
        private FileStream _writeImage;
        private bool _newImage;

        public ComicEditorView()
        {
            InitializeComponent();
            Title = "Add Comic";

            _comicControl = new ComicController();
            _authorControl = new AuthorController();
            _publisherControl = new PublisherController();
            _yearControl = new YearController();
            _rentControl = new RentController();
            _comicStatusControl = new ComicStatusController();

            _authors = _authorControl.GetAllAuthor();
            _publishers = _publisherControl.GetAllPublisher();
            _years = _yearControl.GetAllYear();
            _rents = _rentControl.GetAllRent();
            _comicStatuses = _comicStatusControl.GetAllComicStatus();

            comboBoxAuthor.ItemsSource = _authorControl.GetAllAuthorName();
            comboBoxPublisher.ItemsSource = _publisherControl.GetAllPublisherName();
            comboBoxYear.ItemsSource = _yearControl.GetAllYearNumber();
            comboBoxRent.ItemsSource = _rentControl.GetAllRentRate();

            ClearImageViewer();
        }

        public ComicEditorView(Comic comic)
        {
            InitializeComponent();
            Title = "Edit Comic";

            _comicControl = new ComicController();
            _authorControl = new AuthorController();
            _publisherControl = new PublisherController();
            _yearControl = new YearController();
            _rentControl = new RentController();
            _comicStatusControl = new ComicStatusController();

            _authors = _authorControl.GetAllAuthor();
            _publishers = _publisherControl.GetAllPublisher();
            _years = _yearControl.GetAllYear();
            _rents = _rentControl.GetAllRent();
            _comicStatuses = _comicStatusControl.GetAllComicStatus();

            comboBoxAuthor.ItemsSource = _authorControl.GetAllAuthorName();
            comboBoxPublisher.ItemsSource = _publisherControl.GetAllPublisherName();
            comboBoxYear.ItemsSource = _yearControl.GetAllYearNumber();
            comboBoxRent.ItemsSource = _rentControl.GetAllRentRate();

            _comic = comic;

            textBoxId.Text = comic.Id.ToString();
            textBoxTitle.Text = comic.Title;
            comboBoxAuthor.SelectedItem = _authorControl.GetAuthorName(comic.Author);
            comboBoxPublisher.SelectedItem = _publisherControl.GetPublisherName(comic.Publisher);
            comboBoxYear.SelectedItem = _yearControl.GetYearNumber(comic.Year);
            comboBoxRent.SelectedItem = _rentControl.GetRentRate(comic.Rent);

            _imageUrl = _comicControl.GetComicUrl(comic);
            _oldImageUrl = _comicControl.GetComicUrl(comic);


            try
            {
                var bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.UriSource = new Uri(@"C:\xampp\htdocs\ComicQImage\" + _imageUrl);
                bmp.EndInit();
                imageViewer.Source = bmp;
            }
            catch (Exception)
            {
                var bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.UriSource = new Uri(@"C:\xampp\htdocs\ComicQImage\defaultdefaultdefault.bmp");
                bmp.EndInit();
                imageViewer.Source = bmp;
            }
        }

        private void ClearTextBox()
        {
            textBoxId.Text = "";
            textBoxTitle.Text = "";
            comboBoxAuthor.SelectedItem = null;
            comboBoxPublisher.SelectedItem = null;
            comboBoxYear.SelectedItem = null;
            comboBoxRent.SelectedItem = null;
        }

        private static void ReadWriteStream(Stream readStream, Stream writeStream)
        {
            const int length = 256;
            var buffer = new Byte[length];
            var bytesRead = readStream.Read(buffer, 0, length);

            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = readStream.Read(buffer, 0, length);
            }

            readStream.Close();
            writeStream.Close();
        }

        private static string GenerateFileName()
        {
            var path = Path.GetRandomFileName();
            path = path.Replace(".", "");
            return path;
        }

        private void ClearImageViewer()
        {
            var bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.UriSource = new Uri(@"C:\xampp\htdocs\ComicQImage\defaultdefaultdefault.bmp");
            bmp.EndInit();

            imageViewer.Source = bmp;
            _imageUrl = "defaultdefaultdefault.bmp";
        }

        private void ButtonSaveClick(object sender, RoutedEventArgs e)
        {
            if (textBoxTitle.Text.Equals("") || comboBoxAuthor.SelectedItem == null || 
                comboBoxPublisher.SelectedItem == null || comboBoxYear.SelectedItem == null || 
                comboBoxRent.SelectedItem == null || imageViewer.Source == null)
            {
                MessageBox.Show("field tidak boleh kosong");
            }
            else
            {
                if (Title.Equals("Add Comic"))
                {
                    var comic = new Comic
                                    {
                                        Title = textBoxTitle.Text,
                                        Author = _authors[comboBoxAuthor.SelectedIndex],
                                        Publisher = _publishers[comboBoxPublisher.SelectedIndex],
                                        Year = _years[comboBoxYear.SelectedIndex],
                                        Rent = _rents[comboBoxRent.SelectedIndex],
                                        ComicStatus = _comicStatuses[0],
                                        Image = _imageUrl
                                    };

                    _comicControl.AddComic(comic);
                    ClearTextBox();
                    MessageBox.Show("sukses menambah comic");

                    if (_imageUrl != "defaultdefaultdefault.bmp")
                    {
                        _writeImage = new FileStream(@"C:\xampp\htdocs\ComicQImage\" + _imageUrl, FileMode.Create, FileAccess.Write);
                        ReadWriteStream(_readImage, _writeImage);
                    }

                    ClearImageViewer();
                }
                else
                {
                    var newComic = new Comic
                                       {
                                           Id = _comic.Id,
                                           Title = textBoxTitle.Text,
                                           Author = _authors[comboBoxAuthor.SelectedIndex],
                                           Publisher = _publishers[comboBoxPublisher.SelectedIndex],
                                           Year = _years[comboBoxYear.SelectedIndex],
                                           Rent = _rents[comboBoxRent.SelectedIndex],
                                           ComicStatus = _comic.ComicStatus,
                                           Image = _imageUrl
                                       };

                    _comicControl.EditComic(newComic);
                    MessageBox.Show("sukses mengedit comic");

                    if (_imageUrl != "defaultdefaultdefault.bmp")
                    {
                        if (_newImage)
                        {
                            _writeImage = new FileStream(@"C:\xampp\htdocs\ComicQImage\" + _imageUrl, FileMode.Create, FileAccess.Write);
                            ReadWriteStream(_readImage, _writeImage);

                            try
                            {
                                File.Delete(@"C:\xampp\htdocs\ComicQImage\" + _oldImageUrl);
                            }
                            // ReSharper disable EmptyGeneralCatchClause
                            catch (Exception)
                            // ReSharper restore EmptyGeneralCatchClause
                            {
                            }
                        }
                    }
                }
            }
        }

        private void ButtonCancelClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void ButtonAddImageClick(object sender, RoutedEventArgs e)
        {
            var open = new OpenFileDialog {Filter = "Bitmap Images|*.bmp", Title = "Open Image"};
            var result = open.ShowDialog();

            if (result != true) return;

            var bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.UriSource = new Uri(open.FileName);
            bmp.EndInit();

            imageViewer.Source = bmp;

            do
            {
                _imageUrl = GenerateFileName() + ".bmp";
            } while (_comicControl.HasComicUrl(_imageUrl));

            _newImage = true;
            _readImage = open.OpenFile();
        }

        private void ButtonClearImageClick(object sender, RoutedEventArgs e)
        {
            ClearImageViewer();
        }
    }
}
